package com.ocom.payhandle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.entity.pay.EntityFaceErr;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.vo.pay.FaceErrVo;
import com.ocom.mysql.aspect.DataSourceAspect;
import com.ocom.payhandle.dao.IDaoFaceErr;
import com.ocom.payhandle.service.FaceErrService;
import com.ocom.payhandle.service.PersonnelInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
public class FaceErrServiceImpl extends ServiceImpl<IDaoFaceErr, EntityFaceErr> implements FaceErrService {

    @Autowired
    PersonnelInfoService personnelInfoService;

    @Override
    @DataSourceAspect(type = DataSourceEnum.PART_DB)
    public void Add(Long companyId,FaceErrVo faceErrVo) {

        Date date = new Date();
        date.setTime(faceErrVo.getTimestamp());

        UpdateWrapper<EntityFaceErr> updateWrapper=new UpdateWrapper<>();
        updateWrapper.set("status",0);
        updateWrapper.eq("com_id",faceErrVo.getComId());
        updateWrapper.eq("device_no",faceErrVo.getDeviceNo());
        updateWrapper.lt("update_time",date);
        this.update(updateWrapper);

        for (Long pid : faceErrVo.getIds()){
            EntityPersonnelInfo entityPersonnelInfo = personnelInfoService.selectPersonnel(faceErrVo.getComId(),pid);
            if(entityPersonnelInfo==null){
                continue;
            }

            QueryWrapper<EntityFaceErr> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("com_id",faceErrVo.getComId());
            queryWrapper.eq("device_no",faceErrVo.getDeviceNo());
            queryWrapper.eq("p_id",pid);

            EntityFaceErr entityFaceErr= new EntityFaceErr();
            entityFaceErr.setComId(faceErrVo.getComId());
            entityFaceErr.setDeviceNo(faceErrVo.getDeviceNo());
            entityFaceErr.setPId(pid);
            entityFaceErr.setDeviceType(faceErrVo.getDeviceType());
            entityFaceErr.setStatus(1);
            if(!CommonUtil.isNull(entityPersonnelInfo.getPPhotoUrl2())){
                entityFaceErr.setPhoto(entityPersonnelInfo.getPPhotoUrl2());
            }else{
                entityFaceErr.setPhoto(entityPersonnelInfo.getPPhotoUrl());
            }
            this.saveOrUpdate(entityFaceErr,queryWrapper);
        }
    }
}
